package com.cjy.hd12;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class SelfSortApp {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        Job job= Job.getInstance(conf,"sort");

        job.setJarByClass(SelfSortApp.class);
        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyRuducer.class);

        job.setMapOutputKeyClass(Tripltem.class);
        job.setMapOutputValueClass(Tripltem.class);

        job.setOutputKeyClass(Tripltem.class);
        job.setOutputValueClass(NullWritable.class);

        FileInputFormat.addInputPath(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        System.exit(job.waitForCompletion(true)?0:1);
    }
    public static class MyMapper extends Mapper<LongWritable, Text,Tripltem,Tripltem> {
        @Override
        protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException {
            String[] items = value.toString().split(",");
            Tripltem tripltem = new Tripltem(items[0],Integer.parseInt(items[1]),Integer.parseInt(items[2]));
            context.write(tripltem,tripltem);
        }
    }
    public static class MyRuducer extends Reducer<Tripltem,Tripltem,Tripltem, NullWritable>{
        @Override
        protected void reduce(Tripltem key, Iterable<Tripltem> values, Context context) throws IOException, InterruptedException {
            for (Tripltem t:values){
                context.write(t,NullWritable.get());
            }
        }
    }
}
